﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Se7en.Admin.Model;
using ERMSys.Framework.Utilities;

namespace Se7en.Admin.Business
{
    partial class AccountingBLL
    {
        public static Menu Menu_GetById(this AdminContext context, int menuId)
        {
            return context.Menus.FirstOrDefault(m => m.MenuID == menuId);
        }

        public static List<Menu> Menu_GetAll(this AdminContext context, int pageIndex, int pageSize, out int total)
        {
            return context.Menus.OrderBy(m => m.Order).ToListPaging(pageIndex, pageSize, out total);
        }

        public static int Menu_GetMaxOrder(this AdminContext context)
        {
            if (context.Menus.Count() == 0)
                return 0;
            return context.Menus.Max(m => m.Order);
        }

        public static int Menu_GetMaxOrder(this AdminContext context, int parentMenuId)
        {
            return context.Menus.Where(m => m.ParentID.HasValue && m.ParentID.Value == parentMenuId).Max(m => m.Order);
        }

        public static void Menu_AddNew(this AdminContext context, Menu menu)
        {
            context.Menus.AddObject(menu);
        }

        public static bool Menu_DeleteById(this AdminContext context, int menuId)
        {
            Menu menu = context.Menu_GetById(menuId);
            if (menu != null && !context.Menus.Any(m => m.ParentID.HasValue && m.ParentID.Value == menuId))
            {
                context.Menus.DeleteObject(menu);

                // Rearrange order of other menus


                return true;
            }

            return false;
        }

        public static List<Menu> Menu_GetByUserID(this AdminContext context, int userID)
        {
            List<UserRole> userRoles = context.UserRoles.Where(ur => ur.UserID == userID).ToList();
            List<Menu> menus = new List<Menu>();
            foreach (UserRole us in userRoles)
            {
                if (us.RoleID.HasValue)
                {
                    menus.AddRange(context.RoleMenus.Where(m => m.RoleID == us.RoleID.Value).Select(m => m.Menu).ToList());
                }
                else
                {
                    return context.Menus.ToList();
                }
            }
            return menus;
        }
    }
}
